﻿using System;
using System.IO;
using System.Net;
using System.Text;
using Framework.Modelo.ExtensionesBásicas;

namespace Framework.CapaDeDatos.AccesoADatos
{
    public class Http : IAccesoADatos
    {
        #region IAccesoADatos Members

        public String Recuperar(String query)
        {
            Boolean isUri = Uri.IsWellFormedUriString(query, UriKind.Absolute);
            if (isUri)
                return MakeRequest(new Uri(query), HttpVerb.GET, null);
            else
                return null;
        }

        public String Guardar(String query, String postData)
        {
            Boolean isUri = Uri.IsWellFormedUriString(query, UriKind.Absolute);
            if (isUri)
                return MakeRequest(new Uri(query), HttpVerb.GET, postData);
            else
                return null;
        }

        #endregion

        #region Private Members

        private String MakeRequest(Uri url, HttpVerb httpVerb, Object postData)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = httpVerb.ToString();
            if (httpVerb == HttpVerb.POST)
            {
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] postDataBytes = null;
                if (postData.GetType() == typeof(String))
                switch (postData.GetType().FullName)
                { 
                    case "System.String":
                        postDataBytes = encoding.GetBytes((String)postData);
                        break;
                    default:
                        postDataBytes = (byte[])postData;
                        break;
                }
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postDataBytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postDataBytes, 0, postDataBytes.Length);
                requestStream.Close();
            }

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                return reader.ReadToEnd();
            }
            catch (WebException e)
            {
                return null;
            }
        }

        #endregion
    }
}
